package com.videostar.funforfollowers;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.webkit.WebView;

import com.likes.followers.insta.more.free.BuildConfig;
import com.tencent.shadow.core.common.LoggerFactory;
import com.tencent.shadow.dynamic.host.DynamicRuntime;
import com.videostar.funforfollowers.ui.activity.MainActivity;
import com.videostar.funforfollowers.utils.AppsflyerUtils;
import com.zhouyou.http.EasyHttp;

import static android.os.Process.myPid;

/**
 * @author LLhon
 * @Project Android-Video-Editor
 * @Package com.marvhong.videoeditor
 * @Date 2018/8/21 16:00
 * @description
 */
public class App extends Application {

    public static Context sApplication;
    public static Boolean debug;

    @Override
    public void onCreate() {
        super.onCreate();
        debug = BuildConfig.DEBUG;
        sApplication = getApplicationContext();

        AppsflyerUtils.INSTANCE.init(this, "TvXqBky4vipNih7Q6ncxpn", debug);

        EasyHttp.init(this);
        LoggerFactory.setILoggerFactory(new MainActivity.Companion.MyLog());

        if (isProcess(this, ":image_handle")) {
            //在全动态架构中，Activity组件没有打包在宿主而是位于被动态加载的runtime，
            //为了防止插件crash后，系统自动恢复crash前的Activity组件，此时由于没有加载runtime而发生classNotFound异常，导致二次crash
            //因此这里恢复加载上一次的runtime
            DynamicRuntime.recoveryRuntime(this);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                WebView.setDataDirectorySuffix("image_handle");
            }
        }
        if (BuildConfig.DEBUG) {
            EasyHttp.getInstance()
                    .debug("EasyHttp", true);

        }
    }

    public static void saveCoins(Long coins) {
        sApplication.getSharedPreferences("coins", Context.MODE_PRIVATE).edit().putLong("coins", coins).apply();
    }

    public static Long getCoins(){
        return sApplication.getSharedPreferences("coins", Context.MODE_PRIVATE).getLong("coins", 100);
    }

    public static Long  reduceCoins() {
        Long coins = getCoins() - 10;
        if (coins >= 0) {
            saveCoins(coins);
        }
        return coins;
    }

    private static boolean isProcess(Context context, String processName) {
        String currentProcName = "";
        ActivityManager manager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == myPid()) {
                currentProcName = processInfo.processName;
                break;
            }
        }

        return currentProcName.endsWith(processName);
    }

}


